import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {Router} from '@angular/router';
import {LoadingService} from '../../shared/loading.service';
import {Md5} from 'ts-md5/dist/md5';
@Component({
  templateUrl: 'login.component.html'
})
export class LoginComponent {
  public userName: any;
  public passWord: any;
  public type: String = '';
  constructor(public http: Http,
              private router: Router,
              private loading: LoadingService,
              ) {
  }
  OnInit () {

  }
  login() {
    if (this.userName === undefined && this.passWord === undefined) {
      alert('账号/密码不能为空');
    } else if (this.userName === '' && this.passWord === '') {
      alert('账号/密码不能为空');
    } else if (this.userName === undefined || this.userName === '') {
      alert('请输入用户名');
    } else if (this.passWord === undefined || this.passWord === '') {
      alert('请输入密码');
    } else {
      const params = {
        account: this.userName,
        password: this.passWord,
      };
      this.loading.show();
      this.http.post(ROOT_URL + 'Login/login', params).subscribe((result) => {
        this.loading.hide();
        result = result.json();
        if (result['code'] === 0) {
          if (result['data']['name']) {
            localStorage.userName = result['data']['name'];
          }else {
            localStorage.userName = '';
          }
          localStorage.tokenTime = result['time'];
          localStorage.type = result['data']['type'];
          localStorage.token = result['data']['token'];
          localStorage.id = result['data']['id'];
          localStorage.account = this.userName;
          console.log(result['data']['permissions'])
          localStorage.permissions = JSON.stringify(result['data']['permissions']);
          if (result['data']['permissions'][0].controller) {
            this.router.navigateByUrl(result['data']['permissions'][0].controller ? (result['data']['permissions'][0].controller + '/index') : 'login');
          }else {
            alert('页面好像丢了');
          }
        }else {
          alert(result['msg']);
        }
      });
    }

  }

  keyEvent(e) {
    if (e.keyCode === 13) {
      this.login();
    }
  }



}
